<?php
class OrdersController extends AppController {

	var $name = 'Orders';

	var $permissions = array(
		'add' => array('admin','manag'),
		'index' => array('admin','manag'),
		'view' => array('admin','manag','emplo','firms'),
		'edit' => array('admin','manag'),
		'delete' => array('admin','manag')
	);
	
	public $presetVars = array(
		array('field' => 'numer', 'type' => 'like'),
		array('field' => 'name', 'type' => 'like'),
		array('field' => 'payment_status', 'type' => 'value'),
		array('field' => 'status_of_implementation', 'type' => 'value'),
		array('field' => 'type_of_service_id', 'type' => 'value'),
		array('field' => 'types_of_spaces_id', 'type' => 'value')
	);
	
		
	function beforeFilter(){
		parent::beforeFilter();
		$this->set(OrdersController::dictionaries());
	}
	
	static function dictionaries(){
		$typeOfCycles = array(			
			1=>__("Repeat every month",true),
			2=>__("Repeat every week",true),
			3=>__("Repeat every day",true),
			4=>__("Order one-off",true)
		);
		
		$paymentStatus = array(
			1=>__("do zaplaty",true),
			2=>__("zaplacono",true)
		);
		$statusOfImplementation = array(
			1=>__("do wykonania",true),
			2=>__("wykonane",true),
			3=>__("nie wykonane",true),
			4=>__("anulowane",true)
		);
		return compact('typeOfCycles', 'paymentStatus','statusOfImplementation');		
	}

	function index() {
		$this->Order->recursive = 0;
		$this->set('orders', $this->paginate());	
 		$typeOfServices = $this->Order->TypeOfService->find('list');
		$typesOfSpaces = $this->Order->TypesOfSpaces->find('list');
		$this->set(compact('typeOfServices', 'typesOfSpaces'));
	}
	
	
	public function find() {
		$this->Prg->commonProcess();
		$this->paginate['conditions'] = $this->Order->parseCriteria($this->passedArgs);
		$this->set('orders', $this->paginate());
		$typeOfServices = $this->Order->TypeOfService->find('list');
		$typesOfSpaces = $this->Order->TypesOfSpaces->find('list');
		$this->set(compact('typeOfServices', 'typesOfSpaces'));
		
		$this->autoRender = false;
		$this->render('index');
	}

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__("Invalid order", true));
			$this->redirect(array('action' => 'index'));
		}
		$typeOfWorks = $this->Order->Employee->TypeOfWork->find('list');
		$order =  $this->Order->read(null, $id);
		$this->set(compact('order','typeOfWorks'));
	}

	function add() {
		if (!empty($this->data)) {
			$this->Order->set($this->data);
			if ($this->Order->validates($this->data) && count($this->data['Employee']) != 0) {
				$order['Order'] = $this->data['Order'];
				$this->Order->create();
				if ($this->Order->save($order)) {
					$order_id = $this->Order->getLastInsertID();
					$this->_add_employee($order_id);
					$this->_add_orders_cycle($order_id);
					$this->_add_orders_breakes($order_id);
					$this->Session->setFlash(__("The order has been saved", true));
					
					$this->redirect(array('action' => 'index'));
				} else {
					$this->Session->setFlash(__("The order could not be saved. Please, try again. blad zapisu", true));
				} 
			}else{
				$this->Session->setFlash(__("The order could not be saved. Please, try again. validacja", true));
			}
		}
		$customers = $this->Order->Customer->find('all');
		$typeOfServices = $this->Order->TypeOfService->find('list');
		$typesOfSpaces = $this->Order->TypesOfSpaces->find('list');
		$typeOfWorks = $this->Order->Employee->TypeOfWork->find('list');
		$employees = $this->Order->Employee->find('all',array('conditions'=>array('User.group'=>'emplo')));
		$this->set(compact('customers', 'typeOfServices', 'typesOfSpaces', 'employees','typeOfWorks'));
	}
	
	private function _add_employee($order_id){

		foreach ($this->data['Employee'] as $employee_id => $e) {
			$employee = null;
			if($e['employee_id'] == $employee_id ){	
				
				$employee['OrdersEmployee']['orders_id'] = $order_id;
				$employee['OrdersEmployee']['employee_id'] = $employee_id;
				$employee['OrdersEmployee']['percent'] = $e['percent'];
				$employee['OrdersEmployee']['amount'] = $e['amount'];
				$this->Order->OrdersEmployee->create();
				if ($this->Order->OrdersEmployee->save($employee)){
							
				}else{
					$this->Session->setFlash(__("Error writing to the worker's job", true));
				}
			}
		}
	}
	
	private function _edit_employee($order_id){
		$old_data = $this->Order->read(null, $order_id);
		
		//usuwamy
		foreach ($old_data['Employee'] as $key => $employee) {
			if(array_key_exists($employee['id'], $this->data['OrdersEmployee']) &&  $this->data['OrdersEmployee'][$employee['id']] == $employee['id'] ){
				$this->Order->OrdersEmployee->save($employee);
				unset($this->data['OrdersEmployee'][$employee['id']]);
			}else{
				$this->Order->OrdersEmployee->delete($employee['OrdersEmployee']['id']);
			}
		}

		foreach ($this->data['OrdersEmployee'] as $employee_id => $e) {
			$employee_ = null;
			if($e['employee_id'] == $employee_id){	
				
				$employee_['OrdersEmployee']['orders_id'] = $order_id;
				$employee_['OrdersEmployee']['employee_id'] = $employee_id;
				$employee_['OrdersEmployee']['percent'] = $e['percent'];
				$employee_['OrdersEmployee']['amount'] = $e['amount'];
				$this->Order->OrdersEmployee->create();
				if ($this->Order->OrdersEmployee->save($employee_)){
							
				}else{
					$this->Session->setFlash(__("Error writing to the worker's job", true));
				}
			}
		}
	}
	
	private function _add_orders_cycle($order_id){
		switch($this->data['OrdersCycle']['type_of_cycle_id']){
			case '1':
				foreach ($this->data['OrdersCycle_m'] as $day_ => $value){
					$this->data['OrdersCycle'][$day_] = $value;
				}
				break;
			case '2':
				foreach ($this->data['OrdersCycle_w'] as $day_ => $value){
					$this->data['OrdersCycle'][$day_] = $value;				
				}
				break;	
		}
		$this->data['OrdersCycle']['date_start'] = $this->EuroDate->convert($this->data['Order']['date_start'],"Y-m-d");
		$this->data['OrdersCycle']['date_end'] = $this->EuroDate->convert($this->data['OrdersCycle']['date_end'],"Y-m-d");
		$this->data['OrdersCycle']['orders_id'] = $order_id;
		$this->Order->OrdersCycle->create();
		if ($this->Order->OrdersCycle->save($this->data)){					
		}else{
			$this->Session->setFlash(__("Error writing to the time cycle for order", true));
		}
	}
	
	private function _edit_orders_cycle($order_id){
		switch($this->data['OrdersCycle']['type_of_cycle_id']){
			case '1':
				foreach ($this->data['OrdersCycle_m'] as $day_ => $value){
					$this->data['OrdersCycle'][$day_] = $value;
				}
				break;
			case '2':
				foreach ($this->data['OrdersCycle_w'] as $day_ => $value){
					$this->data['OrdersCycle'][$day_] = $value;				
				}
				break;	
		}
		$this->data['OrdersCycle']['date_start'] = $this->EuroDate->convert($this->data['Order']['date_start'],"Y-m-d");
		$this->data['OrdersCycle']['date_end'] = $this->EuroDate->convert($this->data['OrdersCycle']['date_end'],"Y-m-d");
		$this->data['OrdersCycle']['orders_id'] = $order_id;
		if ($this->Order->OrdersCycle->save($this->data)){					
		}else{
			$this->Session->setFlash(__("Error writing to the time cycle for order", true));
		}
	}
		
	private function _add_orders_breakes($order_id){
		if(!isset($this->data['OrdersBreak']) || !is_array($this->data['OrdersBreak'])) return;
		foreach ($this->data['OrdersBreak'] as $key => $b) {
			if(!empty($b['date_start'])){
				$break = array();
				$break['OrdersBreak']['orders_id'] = $order_id;
				$break['OrdersBreak']['date_start'] =  $this->EuroDate->convert($b['date_start'],"Y-m-d");
				$break['OrdersBreak']['date_end'] =  $this->EuroDate->convert($b['date_end'],"Y-m-d");
				if ($this->Order->OrdersBreak->save($break)){					
				}else{
					$this->Session->setFlash(__("Error writing to the breaks", true));
				}
			}
		}
	}	

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__("Invalid order", true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {	
			$this->Order->set($this->data);		
			if ($this->Order->validates($this->data) && count($this->data['OrdersEmployee']) != 0) {
				$order['Order'] = $this->data['Order'];
				if ($this->Order->save($this->data['Order']['id'])) {					
					$this->_edit_employee($this->data['Order']['id']);
					$this->_edit_orders_cycle($this->data['Order']['id']);
//					$this->_add_orders_breakes($this->data['Order']['id']);
					$this->Session->setFlash(__("The order has been saved", true));
					
					$this->redirect(array('action' => 'index'));
				} else {
					$this->Session->setFlash(__("The order could not be saved. Please, try again. blad zapisu", true));
				} 
			}else{
				$this->Session->setFlash(__("The order could not be saved. Please, try again. validacja", true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Order->read(null, $id);
			// przygotowanie danych pracownikow do edycji
			foreach ($this->data['Employee'] as $key => $employee) {
				$this->data['OrdersEmployee'][$employee['id']] = $employee['OrdersEmployee'];
			}	
			//przygotowanie danych o cyklach do edycji
			switch($this->data['OrdersCycle']['type_of_cycle_id'] ){
				case 1:
					$this->data['OrdersCycle_m'] = $this->data['OrdersCycle'];
					break;
				case 2: 
					$this->data['OrdersCycle_w'] = $this->data['OrdersCycle'];
			}		
		}
		$customers = $this->Order->Customer->find('all');
		$typeOfServices = $this->Order->TypeOfService->find('list');
		$typesOfSpaces = $this->Order->TypesOfSpaces->find('list');	
		$typeOfWorks = $this->Order->Employee->TypeOfWork->find('list');	
		$employees = $this->Order->Employee->find('all',array('conditions'=>array('User.group'=>'emplo')));

		$this->set(compact('customers', 'typeOfServices', 'typesOfSpaces', 'employees','typeOfWorks'));
		
	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__("Invalid id for order", true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Order->delete($id,true)) {

			$this->Order->OrdersCycle->deleteAll(array('OrdersCycle.orders_id'=>$id));
			$this->Order->OrdersBreak->deleteAll(array('OrdersBreak.orders_id'=>$id));
			$this->Order->OrdersSeries->deleteAll(array('OrdersSeries.orders_id'=>$id));
			$this->Order->OrdersEmployee->deleteAll(array('OrdersEmployee.orders_id'=>$id));
			
			$this->Session->setFlash(__("Order deleted", true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__("Order was not deleted", true));
		$this->redirect(array('action' => 'index'));
	}

}
?>